package com.gedeshidai.shumadevelop.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.gedeshidai.shumadevelop.common.BaseResponse;
import com.gedeshidai.shumadevelop.common.ErrorCode;
import com.gedeshidai.shumadevelop.common.ResultUtils;
import com.gedeshidai.shumadevelop.exception.BusinessException;
import com.gedeshidai.shumadevelop.mapper.UserMapper;
import com.gedeshidai.shumadevelop.model.dto.user.CheckRequest;
import com.gedeshidai.shumadevelop.model.entity.History;
import com.gedeshidai.shumadevelop.model.entity.Product;
import com.gedeshidai.shumadevelop.model.entity.User;
import com.gedeshidai.shumadevelop.model.enums.*;
import com.gedeshidai.shumadevelop.model.vo.UserVO;
import com.gedeshidai.shumadevelop.service.HistoryService;
import com.gedeshidai.shumadevelop.service.ProductService;
import com.gedeshidai.shumadevelop.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import static com.gedeshidai.shumadevelop.constant.UserConstant.USER_LOGIN_STATE;


/**
 * 用户服务实现
 *
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    

    @Resource
    @Lazy
    private ProductService productService;

    @Resource
    private HistoryService historyService;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    /**
     * 盐值，混淆密码
     */
    public static final String SALT = "gedeshidai";

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        synchronized (userAccount.intern()) {
            // 账户不能重复
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_account", userAccount);
            long count = this.baseMapper.selectCount(queryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
            }
            // 2. 加密
            String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
            // 3. 插入数据
            User user = new User();
            user.setUserAccount(userAccount);
            user.setUserPassword(encryptPassword);
            user.setUserName("用户" + RandomStringUtils.randomAlphanumeric(10));
            boolean saveResult = this.save(user);
            if (!saveResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
            }
            return user.getUserId();
        }
    }

    @Override
    public UserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        queryWrapper.eq("user_password", encryptPassword);
        User user = this.getOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        // 3. 记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, user);
        return this.getLoginUserVO(user);
    }



    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getUserId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 从数据库查询（追求性能的话可以注释，直接走缓存）
        long userId = currentUser.getUserId();
        currentUser = this.getById(userId);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }

    /**
     * 获取当前登录用户（允许未登录）
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUserPermitNull(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getUserId() == null) {
            return null;
        }
        // 从数据库查询（追求性能的话可以注释，直接走缓存）
        long userId = currentUser.getUserId();
        return this.getById(userId);
    }

    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    @Override
    public boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        return isAdmin(user);
    }

    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }

    /**
     * 用户注销
     *
     * @param request
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {
        if (request.getSession().getAttribute(USER_LOGIN_STATE) == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }
        // 移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;
    }

    @Override
    public UserVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO loginUserVO = new UserVO();
        BeanUtils.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public List<UserVO> getUserVO(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    @Transactional
    @Override
    public BaseResponse<Boolean> goCheck(CheckRequest checkRequest, HttpServletRequest request){
        //获取用户信息
        User loginUser = this.getLoginUser(request);
        if(ObjectUtils.isEmpty(checkRequest.getId())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //获得商品的审核状态
        Product product=productService.getById(checkRequest.getId());
        if(ObjectUtils.isEmpty(product)){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //判断用户是否有权限操作
        if(!loginUser.getUserId().equals(product.getUserId())){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        int state=product.getProductCheckState();
        //判断状态是否为空
        if(ObjectUtils.isEmpty(state)){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        //商品的审核状态为未审核/审核驳回时可以发起审核
        if(state== ProductCheckStateEnum.NO_CHECK.getCode() ||state==ProductCheckStateEnum.BACK_CHECK.getCode()){
            //修改状态为发起审核状态
            product.setProductCheckState(ProductCheckStateEnum.GO_CHECK.getCode());
            //修改店小二操作状态为已提交审核
            product.setProductOwnerState(ProductOwnerStateEnum.SUBMITTED_CHECK.getCode());
            productService.updateById(product);
            History history=new History();
            history.setProductId(product.getProductId());
            history.setStatus(ProductCheckStateEnum.GO_CHECK.getCode());
            Long userId=product.getUserId();
            User user=this.getById(userId);
            history.setUserAccount(user.getUserAccount());
            history.setRemark(checkRequest.getRemark());
            historyService.save(history);
        }else {
            throw new BusinessException(ErrorCode.PRODUCT_CHECK_ERROR);
        }
        return ResultUtils.success(true);
    }

    @Transactional
    @Override
    public BaseResponse<Boolean> goCheckAsync(CheckRequest checkRequest, HttpServletRequest request){
        //线程池实现异步操作
        CompletableFuture.runAsync(() -> {
            //获取用户信息
            User loginUser = this.getLoginUser(request);
            if(ObjectUtils.isEmpty(checkRequest.getId())){
                throw new BusinessException(ErrorCode.PARAMS_ERROR);
            }
            //获得商品的审核状态
            Product product=productService.getById(checkRequest.getId());
            if(ObjectUtils.isEmpty(product)){
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
            }
            //判断用户是否有权限操作
            if(!loginUser.getUserId().equals(product.getUserId())){
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
            int state=product.getProductCheckState();
            //判断状态是否为空
            if(ObjectUtils.isEmpty(state)){
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
            //商品的审核状态为未审核/审核驳回时可以发起审核
            if(state==ProductCheckStateEnum.NO_CHECK.getCode()||state==ProductCheckStateEnum.BACK_CHECK.getCode()){
                //修改状态为发起审核状态
                product.setProductCheckState(ProductCheckStateEnum.GO_CHECK.getCode());
                //修改店小二操作状态为已提交审核
                product.setProductOwnerState(ProductOwnerStateEnum.SUBMITTED_CHECK.getCode());
                productService.updateById(product);
                History history=new History();
                history.setProductId(product.getProductId());
                history.setStatus(ProductCheckStateEnum.GO_CHECK.getCode());
                Long userId=product.getUserId();
                User user=this.getById(userId);
                history.setUserAccount(user.getUserAccount());
                history.setRemark(checkRequest.getRemark());
                historyService.save(history);
            }else {
                throw new BusinessException(ErrorCode.PRODUCT_CHECK_ERROR);
            }
        }, threadPoolExecutor);
        return ResultUtils.success(true);
    }
    @Transactional
    @Override
    public BaseResponse<Boolean> checkPass(CheckRequest checkRequest){
        //获得商品的审核状态
        Product product=productService.getById(checkRequest.getId());
        if(ObjectUtils.isEmpty(product)){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        int state=product.getProductCheckState();
        //商品的审核状态为发起审核时
        if(state== ProductCheckStateEnum.GO_CHECK.getCode()){
            //修改状态为审核通过
            product.setProductCheckState(ProductCheckStateEnum.PASS_CHECK.getCode());
            productService.updateById(product);
            History history=new History();
            history.setProductId(product.getProductId());
            history.setStatus(HistoryStatusEnum.PASS_CHECK.getCode());
            Long userId=product.getUserId();
            User user=this.getById(userId);
            history.setUserAccount(user.getUserAccount());
            history.setRemark(checkRequest.getRemark());
            historyService.save(history);
            //接着调用上线操作方法，用于处理审核通过时间超出上线时间
            List<Long> list=new ArrayList<>();
            list.add(checkRequest.getId());
            setOnLine(list);
        }else {
            throw new BusinessException(ErrorCode.PRODUCT_CHECK_ERROR);
        }
        return ResultUtils.success(true);
    }
    @Transactional
    @Override
    public BaseResponse<Boolean> reCheck(CheckRequest checkRequest){
        //获得商品的审核状态
        Product product=productService.getById(checkRequest.getId());
        if(ObjectUtils.isEmpty(product)){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        int state=product.getProductCheckState();
        //商品的审核状态为发起审核时
        if(state==ProductCheckStateEnum.GO_CHECK.getCode()){
            //修改状态为审核驳回
            product.setProductCheckState(ProductCheckStateEnum.BACK_CHECK.getCode());
            //修改店小二操作状态为已编辑
            product.setProductOwnerState(ProductOwnerStateEnum.EDITED.getCode());
            productService.updateById(product);
            History history=new History();
            history.setProductId(product.getProductId());
            history.setStatus(HistoryStatusEnum.BACK_CHECK.getCode());
            Long userId=product.getUserId();
            User user=this.getById(userId);
            history.setUserAccount(user.getUserAccount());
            history.setRemark(checkRequest.getRemark());
            historyService.save(history);
        }else {
            throw new BusinessException(ErrorCode.PRODUCT_CHECK_ERROR);
        }
        return ResultUtils.success(true);
    }
    @Transactional
    @Override
    public BaseResponse<Boolean> setOffLine(List<Long> list){
        for(Long id:list){
            //判断id是否为空
            if(ObjectUtils.isEmpty(id)){
                throw new BusinessException(ErrorCode.PARAMS_ERROR);
            }
            Product product=productService.getById(id);
            //判断商品是否存在
            if(ObjectUtils.isEmpty(product)){
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
            }
            //判断商品状态是否为空
            if(ObjectUtils.isEmpty(product.getProductOnlineState())){
                throw new BusinessException(ErrorCode.PRODUCT_ONLINE_ERROR);
            }
            //判断当前上线状态是否是已上线
            if(product.getProductOnlineState().equals(ProductOnlineStateEnum.ONLINE.getCode())){
                //将选中商品的状态调整为已下线，未审核
                product.setProductOnlineState(ProductOnlineStateEnum.OFFLINE.getCode());
                product.setProductCheckState(ProductCheckStateEnum.NO_CHECK.getCode());
                //修改店小二操作状态为已编辑
                product.setProductOwnerState(ProductOwnerStateEnum.EDITED.getCode());
                productService.updateById(product);
                History history=new History();
                history.setProductId(product.getProductId());
                history.setStatus(HistoryStatusEnum.OFFLINE.getCode());
                Long userId=product.getUserId();
                User user=this.getById(userId);
                history.setUserAccount(user.getUserAccount());
                history.setRemark("下线通过备注");
                historyService.save(history);
            }else {
                throw new BusinessException(ErrorCode.PRODUCT_ONLINE_ERROR);
            }
        }
        return ResultUtils.success(true);
    }
    @Transactional
    @Override
    public BaseResponse<Boolean> setOnLine(List<Long> list){
        //上线操作需要判断审核状态为审核通过
        for(Long id:list){
            //判断id是否为空
            if(ObjectUtils.isEmpty(id)){
                throw new BusinessException(ErrorCode.PARAMS_ERROR);
            }
            Product product=productService.getById(id);
            //判断商品是否存在
            if(ObjectUtils.isEmpty(product)){
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
            }
            //判断商品状态是否为空
            if(ObjectUtils.isEmpty(product.getProductCheckState())){
                throw new BusinessException(ErrorCode.PRODUCT_CHECK_ERROR);
            }
            //判断当前商品的审核状态是否是审核通过状态
            if(product.getProductCheckState().equals(ProductCheckStateEnum.PASS_CHECK.getCode())){
                //判断上线操作的时间
                Date now=new Date();
                Date onTime=product.getTimeOn();
                Date offTime=product.getTimeOff();
                //1、如果当前时间在上线时间之前
                if(now.before(onTime)){
                    //将选中商品的状态调整为已上线
                    product.setProductOnlineState(ProductOnlineStateEnum.ONLINE.getCode());
                    productService.updateById(product);
                    History history=new History();
                    history.setProductId(product.getProductId());
                    history.setStatus(HistoryStatusEnum.ONLINE.getCode());
                    Long userId=product.getUserId();
                    User user=this.getById(userId);
                    history.setUserAccount(user.getUserAccount());
                    history.setRemark("上线操作备注");
                    historyService.save(history);
                }
                //2、如果当前时间在上线时间之后，下线时间之前
                else if(now.after(onTime)&& now.before(offTime)){
                    //将选中商品的状态调整为已上线
                    product.setProductOnlineState(ProductOnlineStateEnum.ONLINE.getCode());
                    productService.updateById(product);
                    History history=new History();
                    history.setProductId(product.getProductId());
                    history.setStatus(HistoryStatusEnum.ONLINE.getCode());
                    Long userId=product.getUserId();
                    User user=this.getById(userId);
                    history.setUserAccount(user.getUserAccount());
                    history.setRemark("上线操作备注");
                    historyService.save(history);
                }
                //3、如果当前时间在下线时间之后或其他时间
                else {
                    throw new BusinessException(ErrorCode.PRODUCT_ONLINE_TIME);
                }
            }else {
                throw new BusinessException(ErrorCode.PRODUCT_ONLINE_ERROR);
            }
        }
        return ResultUtils.success(true);
    }


}
